<template>
  <el-dialog v-model="dialogVisible" title="导出历史数据" width="800px" :close-on-click-modal="false" @close="handleClose">
    <div class="export-dialog">
      <!-- 维度选择按钮 -->
      <div class="dimension-buttons">
        <el-radio-group v-model="dimension">
          <el-radio-button :value="1">分厂</el-radio-button>
          <el-radio-button :value="2">产线</el-radio-button>
          <el-radio-button :value="3">设备</el-radio-button>
        </el-radio-group>
      </div>

      <!-- 穿梭框 -->
      <div class="transfer-container">
        <el-transfer
          v-model="selectedItems"
          :data="transferData"
          :titles="['可选项', '已选项']"
          :props="{ key: 'id', label: 'name' }"
          filterable
          filter-placeholder="请输入名称"
        />
      </div>

      <!-- 时间范围选择 -->
      <div class="time-range-container">
        <div class="time-label">时间范围：</div>
        <el-date-picker
          v-model="timeRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          format="YYYY-MM-DD HH:mm"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 100%"
        />
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleExport" :loading="exportLoading">导出</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, computed } from "vue"
import { ElMessage } from "element-plus"
import { organByLevel } from "@/api/modules/system"
import { SystemSpace as SystemApi } from "@/api/interface/system"
import { deviceListEnergy } from "@/api/modules/archive"
import { useUserStore } from "@/stores/modules/user"
import dayjs from "dayjs"

// Props
interface Props {
  modelValue: boolean
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false
})

// Emits
const emit = defineEmits<{
  (e: "update:modelValue", value: boolean): void
}>()

// 数据
const dialogVisible = computed({
  get: () => props.modelValue,
  set: val => emit("update:modelValue", val)
})

const dimension = ref<1 | 2 | 3>(1) // 选择的类型：1-分厂，2-产线，3-设备
const selectedItems = ref<number[]>([]) // 选中的项
const timeRange = ref<[string, string] | null>(null) // 时间范围
const exportLoading = ref(false) // 导出加载状态

// 原始数据
const factoryList = ref<SystemApi.OrganByLevel[]>([]) // 分厂列表
const lineList = ref<SystemApi.OrganByLevel[]>([]) // 产线列表
const deviceList = ref<any[]>([]) // 设备列表

// 穿梭框数据
const transferData = computed(() => {
  if (dimension.value === 1) {
    // 分厂数据
    return factoryList.value.map(item => ({
      id: item.id,
      name: item.organName
    }))
  } else if (dimension.value === 2) {
    // 产线数据
    return lineList.value.map(item => ({
      id: item.id,
      name: item.organName
    }))
  } else {
    // 设备数据
    return deviceList.value.map(item => ({
      id: item.id,
      name: item.name
    }))
  }
})

// 方法
// 获取分厂数据
const getFactoryList = async () => {
  try {
    const { data } = await organByLevel(1)
    factoryList.value = data || []
  } catch (error) {
    ElMessage.error("获取分厂数据失败")
  }
}

// 获取产线数据
const getLineList = async () => {
  try {
    const { data } = await organByLevel(2)
    lineList.value = data || []
  } catch (error) {
    ElMessage.error("获取产线数据失败")
  }
}

// 获取设备列表
const getDeviceList = async () => {
  try {
    const { data } = await deviceListEnergy({})
    deviceList.value = data || []
  } catch (error) {
    ElMessage.error("获取设备列表失败")
  }
}

// 监听维度变化，清空选中项
watch(dimension, () => {
  selectedItems.value = []
})

// 监听对话框打开
watch(
  () => props.modelValue,
  val => {
    if (val) {
      // 初始化数据
      dimension.value = 1
      selectedItems.value = []
      timeRange.value = null

      // 加载数据
      getFactoryList()
      getLineList()
      getDeviceList()
    }
  }
)

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
}

// 导出数据
const handleExport = async () => {
  // 验证
  if (selectedItems.value.length === 0) {
    ElMessage.warning("请至少选择一项")
    return
  }

  if (!timeRange.value || timeRange.value.length !== 2) {
    ElMessage.warning("请选择时间范围")
    return
  }

  try {
    exportLoading.value = true

    // 构建参数
    const queryParams = {
      type: dimension.value, // 1-分厂，2-产线，3-设备
      ids: selectedItems.value, // 导出范围ID集合
      startTime: timeRange.value[0], // 开始时间
      endTime: timeRange.value[1] // 结束时间
    }
    // 使用原生fetch完全绕过axios拦截器
    const baseURL = import.meta.env.VITE_API_URL
    const userStore = useUserStore()

    // 构建完整URL
    const queryString = Object.keys(queryParams)
      .filter(key => {
        const value = queryParams[key as keyof typeof queryParams]
        return value !== undefined && value !== null && value !== ""
      })
      .map(key => {
        const value = queryParams[key as keyof typeof queryParams]
        const encodedValue = Array.isArray(value) ? value.join(",") : String(value)
        return `${encodeURIComponent(key)}=${encodeURIComponent(encodedValue)}`
      })
      .join("&")

    const fullUrl = `${baseURL}/history/stat/export?${queryString}`
    console.log("完整URL：", fullUrl)

    const response = await fetch(fullUrl, {
      method: "GET",
      headers: {
        token: userStore.token
      }
    })

    console.log("fetch响应：", response)

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const content = await response.blob()
    console.log("blob内容：", content)

    console.log("最终内容：", content)
    // 创建带正确MIME类型的Blob，解决乱码问题
    const blob = new Blob([content], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    })
    const dimensionName = dimension.value === 1 ? "分厂" : dimension.value === 2 ? "产线" : "设备"
    const fileName = `历史数据_${dimensionName}_${dayjs(new Date().getTime()).format("YYYY-MM-DD HH:mm:ss")}.xlsx`

    if ("download" in document.createElement("a")) {
      // 非IE下载
      const elink = document.createElement("a")
      elink.download = fileName
      elink.style.display = "none"
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放URL 对象
      document.body.removeChild(elink)
    } else {
      // IE10+下载
      ;(navigator as any).msSaveBlob(blob, fileName)
    }

    ElMessage.success("导出成功")
    // // 调用导出接口
    // const response: any = await exportHistoryData(params)

    // // 处理文件下载（response可能是AxiosResponse对象或直接是blob数据）
    // const blobData = response.data || response
    // const blob = new Blob([blobData], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" })
    // const url = window.URL.createObjectURL(blob)
    // const link = document.createElement("a")
    // link.href = url

    // // 生成文件名
    // const dimensionName = dimension.value === 1 ? "分厂" : dimension.value === 2 ? "产线" : "设备"
    // const fileName = `历史数据_${dimensionName}_${new Date().getTime()}.xlsx`
    // link.download = fileName

    // document.body.appendChild(link)
    // link.click()
    // document.body.removeChild(link)
    // window.URL.revokeObjectURL(url)

    // ElMessage.success("导出成功")
    handleClose()
  } catch (error) {
    ElMessage.error("导出失败")
  } finally {
    exportLoading.value = false
  }
}
</script>

<style lang="scss" scoped>
.export-dialog {
  .dimension-buttons {
    margin-bottom: 20px;
    display: flex;
    justify-content: center;
  }

  .transfer-container {
    margin-bottom: 20px;
    display: flex;
    justify-content: center;

    :deep(.el-transfer) {
      .el-transfer-panel {
        width: 280px;
      }
    }
  }

  .time-range-container {
    display: flex;
    align-items: center;
    gap: 10px;

    .time-label {
      flex-shrink: 0;
      font-size: 14px;
      font-weight: 500;
    }
  }
}
</style>
